"""
API路由
"""
from fastapi import APIRouter, HTTPException, BackgroundTasks
from typing import Dict, List, Optional, Any
from datetime import datetime

from ..services.strategy_engine import strategy_engine
from ..services.market_data import market_data_service
from ..services.risk_manager import risk_manager
from ..services.trade_engine import trade_engine
from ..core.database import db_manager

# 创建路由器
router = APIRouter(prefix="/api", tags=["api"])


# 系统状态相关接口
@router.get("/status")
async def get_system_status():
    """获取系统状态"""
    try:
        return {
            "status": "running",
            "timestamp": datetime.now().isoformat(),
            "services": {
                "strategy_engine": strategy_engine.is_running,
                "market_data": market_data_service.is_running,
                "risk_manager": risk_manager.is_running,
                "trade_engine": trade_engine.is_running
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 策略管理相关接口
@router.get("/strategies")
async def get_strategies():
    """获取所有策略"""
    try:
        strategies = strategy_engine.get_strategies()
        return {
            "success": True,
            "data": strategies,
            "count": len(strategies)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/strategies/{strategy_id}")
async def get_strategy(strategy_id: str):
    """获取指定策略"""
    try:
        strategy = strategy_engine.get_strategy(strategy_id)
        if not strategy:
            raise HTTPException(status_code=404, detail="策略不存在")
        
        return {
            "success": True,
            "data": strategy
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/strategies")
async def add_strategy(strategy_data: Dict[str, Any]):
    """添加策略"""
    try:
        success = await strategy_engine.add_strategy(strategy_data)
        if success:
            return {
                "success": True,
                "message": "策略添加成功"
            }
        else:
            raise HTTPException(status_code=400, detail="策略添加失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/strategies/{strategy_id}")
async def remove_strategy(strategy_id: str):
    """移除策略"""
    try:
        success = await strategy_engine.remove_strategy(strategy_id)
        if success:
            return {
                "success": True,
                "message": "策略移除成功"
            }
        else:
            raise HTTPException(status_code=400, detail="策略移除失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/strategies/{strategy_id}/start")
async def start_strategy(strategy_id: str):
    """启动策略"""
    try:
        success = await strategy_engine.start_strategy(strategy_id)
        if success:
            return {
                "success": True,
                "message": "策略启动成功"
            }
        else:
            raise HTTPException(status_code=400, detail="策略启动失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/strategies/{strategy_id}/stop")
async def stop_strategy(strategy_id: str):
    """停止策略"""
    try:
        success = await strategy_engine.stop_strategy(strategy_id)
        if success:
            return {
                "success": True,
                "message": "策略停止成功"
            }
        else:
            raise HTTPException(status_code=400, detail="策略停止失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/strategies/{strategy_id}/parameters")
async def update_strategy_parameters(strategy_id: str, parameters: Dict[str, Any]):
    """更新策略参数"""
    try:
        success = await strategy_engine.update_strategy_parameters(strategy_id, parameters)
        if success:
            return {
                "success": True,
                "message": "策略参数更新成功"
            }
        else:
            raise HTTPException(status_code=400, detail="策略参数更新失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 行情数据相关接口
@router.get("/market-data")
async def get_market_data():
    """获取所有行情数据"""
    try:
        market_data = market_data_service.get_all_market_data()
        
        # 转换格式
        data = {}
        for symbol, md in market_data.items():
            data[symbol] = {
                "symbol": symbol,
                "timestamp": md.timestamp.isoformat(),
                "price": md.close,
                "volume": md.volume,
                "bid_price": md.bid_price,
                "ask_price": md.ask_price,
                "delta": md.delta,
                "gamma": md.gamma,
                "vega": md.vega,
                "theta": md.theta,
                "implied_volatility": md.implied_volatility
            }
        
        return {
            "success": True,
            "data": data
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/market-data/{symbol}")
async def get_symbol_market_data(symbol: str):
    """获取指定品种行情数据"""
    try:
        market_data = market_data_service.get_market_data(symbol)
        if not market_data:
            raise HTTPException(status_code=404, detail="行情数据不存在")
        
        return {
            "success": True,
            "data": {
                "symbol": symbol,
                "timestamp": market_data.timestamp.isoformat(),
                "price": market_data.close,
                "volume": market_data.volume,
                "bid_price": market_data.bid_price,
                "ask_price": market_data.ask_price,
                "delta": market_data.delta,
                "gamma": market_data.gamma,
                "vega": market_data.vega,
                "theta": market_data.theta,
                "implied_volatility": market_data.implied_volatility
            }
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/market-data/{symbol}/historical")
async def get_historical_data(symbol: str, days: int = 30):
    """获取历史数据"""
    try:
        historical_data = await market_data_service.get_historical_data(symbol, days)
        return {
            "success": True,
            "data": historical_data,
            "count": len(historical_data)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/market-data/{symbol}/options")
async def get_option_chain(symbol: str):
    """获取期权链"""
    try:
        option_chain = await market_data_service.get_option_chain(symbol)
        return {
            "success": True,
            "data": option_chain,
            "count": len(option_chain)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 交易相关接口
@router.get("/trades")
async def get_trades(strategy_id: Optional[str] = None, limit: int = 100):
    """获取交易记录"""
    try:
        trades = await db_manager.get_trade_records(strategy_id=strategy_id, limit=limit)
        return {
            "success": True,
            "data": trades,
            "count": len(trades)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/trades/{order_id}")
async def get_trade(order_id: str):
    """获取指定交易"""
    try:
        order_status = trade_engine.get_order_status(order_id)
        if not order_status:
            raise HTTPException(status_code=404, detail="订单不存在")
        
        return {
            "success": True,
            "data": order_status
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/trades/cancel/{order_id}")
async def cancel_trade(order_id: str):
    """取消交易"""
    try:
        result = await trade_engine.cancel_order(order_id)
        if result["success"]:
            return {
                "success": True,
                "message": "订单取消成功"
            }
        else:
            raise HTTPException(status_code=400, detail=result["error"])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 持仓相关接口
@router.get("/positions")
async def get_positions(strategy_id: Optional[str] = None):
    """获取持仓"""
    try:
        positions = await db_manager.get_positions(strategy_id=strategy_id)
        return {
            "success": True,
            "data": positions,
            "count": len(positions)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 风险管理相关接口
@router.get("/risks")
async def get_current_risks():
    """获取当前风险状态"""
    try:
        risks = await risk_manager.get_current_risks()
        
        # 转换格式
        risk_data = []
        for risk in risks:
            risk_data.append({
                "limit_type": risk.limit_type,
                "current_value": risk.current_value,
                "limit_value": risk.limit_value,
                "exceeded": risk.exceeded,
                "message": risk.message
            })
        
        return {
            "success": True,
            "data": risk_data
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/risks/limits")
async def get_risk_limits():
    """获取风险限制"""
    try:
        limits = risk_manager.get_risk_limits()
        return {
            "success": True,
            "data": limits
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/risks/limits/{limit_type}")
async def update_risk_limit(limit_type: str, new_value: float):
    """更新风险限制"""
    try:
        success = await risk_manager.update_risk_limit(limit_type, new_value)
        if success:
            return {
                "success": True,
                "message": "风险限制更新成功"
            }
        else:
            raise HTTPException(status_code=400, detail="风险限制更新失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/risks/alerts")
async def get_risk_alerts(limit: int = 50):
    """获取风险告警"""
    try:
        alerts = risk_manager.get_recent_alerts(limit)
        return {
            "success": True,
            "data": alerts,
            "count": len(alerts)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 回测相关接口
@router.post("/backtest/{strategy_id}")
async def run_backtest(strategy_id: str, backtest_config: Dict[str, Any]):
    """运行回测"""
    try:
        # 这里应该调用回测引擎
        # 现在返回模拟结果
        
        # 模拟回测结果
        result = {
            "strategy_id": strategy_id,
            "start_date": backtest_config.get("start_date", "2024-01-01"),
            "end_date": backtest_config.get("end_date", "2024-12-31"),
            "total_return": 0.15,
            "annual_return": 0.12,
            "sharpe_ratio": 1.2,
            "max_drawdown": 0.08,
            "win_rate": 0.65,
            "total_trades": 156,
            "profit_trades": 101,
            "loss_trades": 55,
            "profit_factor": 1.8,
            "equity_curve": []  # 这里应该是实际的权益曲线数据
        }
        
        # 保存回测结果
        await db_manager.save_backtest_result(result)
        
        return {
            "success": True,
            "data": result
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/backtest/{strategy_id}/results")
async def get_backtest_results(strategy_id: str, limit: int = 10):
    """获取回测结果"""
    try:
        results = await db_manager.get_backtest_results(strategy_id, limit)
        return {
            "success": True,
            "data": results,
            "count": len(results)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 系统管理相关接口
@router.post("/system/start")
async def start_system():
    """启动系统"""
    try:
        # 启动各个服务
        await market_data_service.start()
        await strategy_engine.start()
        await risk_manager.start()
        await trade_engine.start()
        
        return {
            "success": True,
            "message": "系统启动成功"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/system/stop")
async def stop_system():
    """停止系统"""
    try:
        # 停止各个服务
        await trade_engine.stop()
        await risk_manager.stop()
        await strategy_engine.stop()
        await market_data_service.stop()
        
        return {
            "success": True,
            "message": "系统停止成功"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 配置相关接口
@router.get("/config")
async def get_config():
    """获取系统配置"""
    try:
        from ..core.config import settings
        
        config = {
            "app_name": settings.APP_NAME,
            "app_version": settings.APP_VERSION,
            "debug": settings.DEBUG,
            "host": settings.HOST,
            "port": settings.PORT,
            "database_url": settings.DATABASE_URL,
            "redis_host": settings.REDIS_HOST,
            "redis_port": settings.REDIS_PORT,
            "default_capital": settings.DEFAULT_CAPITAL,
            "max_position_size": settings.MAX_POSITION_SIZE,
            "max_daily_loss": settings.MAX_DAILY_LOSS,
            "market_data_interval": settings.MARKET_DATA_INTERVAL,
            "strategy_update_interval": settings.STRATEGY_UPDATE_INTERVAL,
            "broker_type": settings.BROKER_TYPE,
            "subscribed_symbols": settings.SUBSCRIBED_SYMBOLS
        }
        
        return {
            "success": True,
            "data": config
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
